package me.idashu.attg.webService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpSession;

import me.idashu.attg.domain.CollectEntity;
import me.idashu.attg.domain.CommentEntity;
import me.idashu.attg.domain.ContextEntity;
import me.idashu.attg.domain.KeywordsEntity;
import me.idashu.attg.domain.NoteEntity;
import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.domain.UserEntity;
import me.idashu.attg.service.CollectService;
import me.idashu.attg.service.CommentService;
import me.idashu.attg.service.ContextService;
import me.idashu.attg.service.ContributionService;
import me.idashu.attg.service.KeywordsService;
import me.idashu.attg.service.NoteService;
import me.idashu.attg.service.UserService;
import me.idashu.attg.util.SimpleMailSender;
import me.idashu.attg.util.SystemConfig;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MyWebService {
	@Autowired
	private NoteService noteService;
	@Autowired
	private CollectService collectService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private KeywordsService keywordsService;
	@Autowired
	private ContributionService contributionService;
	@Autowired
	private SystemConfig systemConfig;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/insertNote", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject insertNote(@ModelAttribute NoteEntity noteEntity,
			@RequestParam("voices") MultipartFile[] voiceFiles,
			@RequestParam("images") MultipartFile[] imageFiles,
			@RequestParam("videos") MultipartFile[] videoFiles) {
		JSONObject json = new JSONObject();
		try{
			boolean flag = false;
			List<KeywordsEntity> listKey = keywordsService.getAllKeyWords();
			for(int i=0;i<listKey.size();i++){
				KeywordsEntity key = listKey.get(i);
				if(noteEntity.getWord().contains(key.getContent())){
					flag = true;
					break;
				}
			}
			if(flag){
				noteEntity.setTime(new Date());
				StringBuffer sb = new StringBuffer();
				StringBuffer sb2 = new StringBuffer();
				StringBuffer sb3 = new StringBuffer();
				for(int i=0;i<imageFiles.length;i++){
					if(i!=imageFiles.length-1){
						sb.append(uploadImage(imageFiles[i])+";");
					}else{
						sb.append(uploadImage(imageFiles[i]));
					}
				}
				for(int i=0;i<videoFiles.length;i++){
					if(i!=videoFiles.length-1){
						sb.append(uploadImage(videoFiles[i])+";");
					}else{
						sb.append(uploadImage(videoFiles[i]));
					}
				}
				for(int k=0;k<voiceFiles.length;k++){
					if(k!=voiceFiles.length-1){
						sb2.append(uploadImage(voiceFiles[k])+";");
					}else{
						sb2.append(uploadImage(voiceFiles[k]));
					}
				}
				noteEntity.setImage(sb.toString());
				noteEntity.setVoice(sb2.toString());
				noteEntity.setVideo(sb3.toString());
				noteService.insertNote(noteEntity);
				json.put("status", 200);
				json.put("message", "添加发言成功");
			}else{
				json.put("status", 400);
				json.put("message", "发言包含敏感词汇");
			}
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/upNote", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject upNote(@RequestParam("noteId") int noteId) {
		JSONObject json = new JSONObject();
		try{
			noteService.upNote(noteId);
			json.put("status", 200);
			json.put("message", "顶成功");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/downNote", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject downNote(@RequestParam("noteId") int noteId) {
		JSONObject json = new JSONObject();
		try{
			noteService.downNote(noteId);
			json.put("status", 200);
			json.put("message", "踩成功");
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/findAllNote", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject findAllNote(@RequestParam("userId") int userId,@RequestParam("contextId") int contextId,@ModelAttribute PageEntity pageEntity) {
		JSONObject json = new JSONObject();
		try{
			Map<String, Object> param = new HashMap<String, Object>();
			int count1 = noteService.countNoteByContextId(contextId);
			pageEntity.setTotalPage(count1);
			pageEntity.setPageLess(pageEntity.getPage());
			param.put("pageEntity", pageEntity);
			param.put("contextId", contextId);
			List<NoteEntity> listNote = noteService.findAllNote(param);
			for(int i=0;i<listNote.size();i++){
				NoteEntity ne = listNote.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userId", userId);
				map.put("noteId", ne.getId());
				int count = collectService.getCollect(map);
				if(count>0){
					ne.setLike(true);
				}else{
					ne.setLike(false);
				}
				ne.setCommentCount(commentService.commentCount(ne.getId()));
			}
			json.put("status", 200);
			json.put("noteEntity", listNote);
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/insertComment", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject insertComment(@ModelAttribute CommentEntity commentEntity) {
		JSONObject json = new JSONObject();
		try{
			commentEntity.setTime(new Date());
			commentService.insertComment(commentEntity);
			json.put("status", 200);
			json.put("message", "添加评论成功");
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/findCommentByNoteId", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject findCommentByNoteId(@RequestParam("noteId") int noteId) {
		JSONObject json = new JSONObject();
		try{
			List<CommentEntity> listComment = commentService.findCommentByNoteId(noteId);
			json.put("status", 200);
			json.put("listComment", listComment);
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	
	@RequestMapping(value = "/findAllNoteByUserId", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject findAllNoteByUserId(@RequestParam("userId") int userId,@ModelAttribute PageEntity pageEntity) {
		JSONObject json = new JSONObject();
		try{
			Map<String, Object> param = new HashMap<String, Object>();
			int count1 = noteService.countNoteByUserId(userId);
			pageEntity.setTotalPage(count1);
			pageEntity.setPageLess(pageEntity.getPage());
			param.put("pageEntity", pageEntity);
			param.put("userId", userId);
			List<NoteEntity> listNote = noteService.findAllNoteByUserID(param);
			for(int i=0;i<listNote.size();i++){
				NoteEntity ne = listNote.get(i);
				ne.setLike(false);
				ne.setCommentCount(commentService.commentCount(ne.getId()));
			}
			json.put("status", 200);
			json.put("noteEntity", listNote);
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	public String uploadImage(MultipartFile file) {
		String dir = systemConfig.getDir("dir");
		String prodir = systemConfig.getDir("prodir");
		String imgurl = null;
		try {
			InputStream is = file.getInputStream();
			byte[] inOutb = new byte[is.available()];
			String uuid = UUID.randomUUID().toString().replace("-", "");
			FileOutputStream fos = new FileOutputStream(new File(dir + uuid
					+file.getName().substring(file.getName().indexOf("."), file.getName().length())));
			imgurl = prodir + uuid + file.getName().substring(file.getName().indexOf("."), file.getName().length());
			is.read(inOutb);
			fos.write(inOutb);
			is.close();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imgurl;
	}

	@RequestMapping(value = "/allNoteOrderByScore", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject allNoteOrderByScore(@RequestParam("userId") int userId,@RequestParam("contextId") int contextId,@ModelAttribute PageEntity pageEntity) {
		JSONObject json = new JSONObject();
		try{
			Map<String, Object> param = new HashMap<String, Object>();
			int count1 = noteService.countNoteByContextId(contextId);
			pageEntity.setTotalPage(count1);
			pageEntity.setPageLess(pageEntity.getPage());
			param.put("pageEntity", pageEntity);
			param.put("contextId", contextId);
			List<NoteEntity> listNote = noteService.allNoteOrderByScore(param);
			for(int i=0;i<listNote.size();i++){
				NoteEntity ne = listNote.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userId", userId);
				map.put("noteId", ne.getId());
				int count = collectService.getCollect(map);
				if(count>0){
					ne.setLike(true);
				}else{
					ne.setLike(false);
				}
				ne.setCommentCount(commentService.commentCount(ne.getId()));
			}
			json.put("status", 200);
			json.put("noteEntity", listNote);
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/deleteNoteById", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deleteNote(@RequestParam("note_id") int note_id) {
		JSONObject json = new JSONObject();
		try{
			noteService.deleteNote(note_id);
			json.put("status", 200);
			json.put("message", "删除发言成功");
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/deleteContribution", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deleteContribution(@RequestParam("contribution_id") int contribution_id) {
		JSONObject json = new JSONObject();
		try{
			contributionService.deleteContribution(contribution_id);
			json.put("status", 200);
			json.put("message", "删除投稿成功");
		}catch (Exception e) {
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject register(@ModelAttribute UserEntity userEntity,HttpSession session) {
		JSONObject json = new JSONObject();
		try{
			int count = userService.getCountByEmail(userEntity.getEmail());
			if(count>0){
				json.put("status", 400);
				json.put("message","该邮箱已注册");
			}else{
				if(userEntity.getValidateCode().equals(session.getAttribute(userEntity.getEmail()))){
					userService.register(userEntity);
					json.put("status", 200);
					json.put("message", "注册成功");
				}else{
					json.put("status", 400);
					json.put("message","验证码输入错误");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/getValidateCode", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject getValidateCode(@RequestParam("email") String email,HttpSession session) {
		JSONObject json = new JSONObject();
		try{
			Random random = new Random();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < 4; i++) {
				sb.append(String.valueOf(random.nextInt(10)));
			}
			session.setAttribute(email, sb.toString());
			new SimpleMailSender().sendTestMail(email,sb.toString());
			json.put("status", 200);
			json.put("message", "获取验证码成功");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
	
	@RequestMapping(value = "/visitorToMember", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject visitorToMember(@ModelAttribute UserEntity userEntity,HttpSession session) {
		JSONObject json = new JSONObject();
		try{
			int count = userService.getCountByEmail(userEntity.getEmail());
			if(count>0){
				json.put("status", 400);
				json.put("message","该邮箱已注册");
			}else{
				if(userEntity.getValidateCode().equals(session.getAttribute(userEntity.getEmail()))){
					userService.visitorToMember(userEntity);
					json.put("status", 200);
					json.put("message", "注册成功");
				}else{
					json.put("status", 400);
					json.put("message","验证码输入错误");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			json.put("status", 400);
			json.put("message", e.getMessage());
		}
		return json;
	}
}
